﻿using BitShuva.Common;
using BitShuva.Models;
using Raven.Client;
using Raven.Client.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

namespace BitShuva.Controllers
{
    [RoutePrefix("api/requests")]
    public class SongRequestsController : UserContextController
    {
        [Route("pending")]
        public async Task<string> GetPendingRequestedSongId()
        {
            var user = await this.GetUserOrNull();
            if (user == null)
            {
                return null;
            }

            var recentSongRequests = await this.Session
                .Query<SongRequest>()
                .Take(10)
                .ToListAsync();

            // Delete old song requests.
            var recent = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(30));
            recentSongRequests
                .Where(s => s.DateTime < recent)
                .ForEach(this.Session.Delete);

            var validSongRequest = recentSongRequests
                .FirstOrDefault(s => s.DateTime >= recent && !s.PlayedForUserIds.Contains(user.Id));
            if (validSongRequest != null)
            {
                validSongRequest.PlayedForUserIds.Add(user.Id);
                await this.Session.StoreAsync(validSongRequest);
            }

            return Match
                .Value(validSongRequest)
                .PropertyOrDefault(s => s.SongId);
        }

        [HttpPost]
        [Route("request/{songId}")]
        public async Task RequestSong(string songId)
        {
            var user = await GetUserOrNull();
            var songRequest = new SongRequest
            {
                DateTime = DateTime.UtcNow,
                SongId = songId,
                UserId = user.Id
            };

            await this.Session.StoreAsync(songRequest);
        }
    }
}
